from sqlalchemy import or_
from datetime import datetime
from flask import current_app
from app import db
from app.models.user import User
from app.models.user_profile import UserProfile
from app.services.dict_service import DictService
from app.services.profile_validation_service import ProfileValidationService


class UserProfileService:
    """用户资料服务层"""
    
    @staticmethod
    def get_user_profile(user_id, for_public=False):
        """获取用户完整资料"""
        user = User.query.get(user_id)
        if not user:
            return None
        
        # 获取用户基本信息和详细资料
        profile_data = user.to_dict()
        
        # 添加详细资料信息
        if user.profile:
            profile_data['profile'] = user.profile.to_dict()
        else:
            profile_data['profile'] = None
        
        # 脱敏处理（如果为公开展示）
        if for_public:
            profile_data = ProfileValidationService.sanitize_profile_data(
                profile_data, for_public=True
            )
        
        # 添加资料完整度
        completeness_info = ProfileValidationService.calculate_completeness(user_id)
        profile_data['completeness'] = completeness_info
        
        # 添加建议
        if not for_public:  # 只为用户本人显示建议
            profile_data['suggestions'] = ProfileValidationService.get_profile_suggestions(user_id)
        
        return profile_data
    
    @staticmethod
    def update_user_profile(user_id, profile_data):
        """更新用户资料（带验证）"""
        user = User.query.get(user_id)
        if not user:
            return {'success': False, 'error': '用户不存在'}
        
        # 数据验证
        validation_result = ProfileValidationService.validate_profile_data(profile_data)
        if not validation_result['is_valid']:
            return {
                'success': False, 
                'error': '数据验证失败', 
                'validation_errors': validation_result['errors'],
                'warnings': validation_result.get('warnings', [])
            }
        
        try:
            # 更新基本信息
            basic_fields = ['nickname', 'real_name', 'gender', 'birthday', 'height', 'weight', 
                           'signature', 'province', 'city', 'district', 'address']
            
            updated_basic_fields = []
            for field in basic_fields:
                if field in profile_data:
                    value = profile_data[field]
                    # 特殊处理生日字段
                    if field == 'birthday' and value:
                        if isinstance(value, str):
                            try:
                                value = datetime.strptime(value, '%Y-%m-%d').date()
                            except ValueError:
                                continue
                    
                    old_value = getattr(user, field)
                    if old_value != value:
                        setattr(user, field, value)
                        updated_basic_fields.append(field)
            
            # 如果更新了生日，重新计算年龄
            if 'birthday' in updated_basic_fields:
                user.update_age()
            
            # 更新详细资料
            profile_info = profile_data.get('profile', {})
            updated_profile_fields = []
            
            if profile_info:
                profile = user.profile
                if not profile:
                    profile = UserProfile(user_id=user_id)
                    db.session.add(profile)
                
                profile_fields = ['education', 'school', 'major', 'occupation', 'company', 
                                 'position', 'income_range', 'work_city', 'hometown', 
                                 'marital_status', 'housing_status', 'car_status', 'smoking_habit', 'drinking_habit',
                                 'nationality', 'constellation', 'blood_type', 'hobbies', 'hobby_tags',
                                 'personality_traits', 'self_intro']
                
                for field in profile_fields:
                    if field in profile_info:
                        value = profile_info[field]
                        
                        # 处理JSON数组格式的字段
                        if field in ['hobby_tags', 'personality_traits'] and isinstance(value, list):
                            value = DictService.format_dict_values_to_json(value)
                        
                        old_value = getattr(profile, field, None)
                        if old_value != value:
                            setattr(profile, field, value)
                            updated_profile_fields.append(field)
            
            db.session.commit()
            
            # 获取更新后的完整资料
            updated_profile = UserProfileService.get_user_profile(user_id)
            
            return {
                'success': True,
                'data': updated_profile,
                'updated_fields': {
                    'basic': updated_basic_fields,
                    'profile': updated_profile_fields
                },
                'validation_warnings': validation_result.get('warnings', []),
                'message': '资料更新成功'
            }
            
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"更新用户资料异常: {str(e)}")
            return {
                'success': False,
                'error': f'更新失败: {str(e)}'
            }
    
    @staticmethod
    def update_user_status(user_id, status):
        """更新用户状态"""
        user = User.query.get(user_id)
        if not user:
            return None
        
        user.status = status
        db.session.commit()
        return user.to_dict()
    
    @staticmethod
    def delete_user_account(user_id):
        """注销用户账户（软删除）"""
        user = User.query.get(user_id)
        if not user:
            return False
        
        # 将状态设置为注销
        user.status = 5  # 注销状态
        db.session.commit()
        return True
    
    @staticmethod
    def get_user_by_id(user_id, viewer_id=None):
        """根据ID获取用户基本信息"""
        user = User.query.get(user_id)
        if not user:
            return None
        
        # 判断是否为公开展示（非本人查看）
        for_public = viewer_id != user_id if viewer_id else True
        
        return UserProfileService.get_user_profile(user_id, for_public=for_public)
    
    @staticmethod
    def get_completeness_analysis(user_id):
        """获取用户资料完整度分析"""
        return ProfileValidationService.calculate_completeness(user_id)
    
    @staticmethod
    def get_profile_suggestions(user_id):
        """获取资料完善建议"""
        return ProfileValidationService.get_profile_suggestions(user_id)
    
    @staticmethod
    def validate_profile_data(profile_data):
        """验证资料数据"""
        return ProfileValidationService.validate_profile_data(profile_data) 